import time
import cv2
import math
import numpy as np
import Processor.Converter as Converter

from PyQt5.QtWidgets import QDialog
from PyQt5.QtGui import QColor
from Plugin.gamma.gamma_design import Ui_GammaController


class GammaController(QDialog, Ui_GammaController):
    layer = None  # 图层
    mat = None  # 原始Mat 数据

    def __init__(self, parent, mat=None):
        super().__init__(parent)
        self.setupUi(self)
        self.initUI(parent)
        self.mat = mat

    def reject(self):
        """
        取消操作
        :return:
        """
        image = Converter.Numpy2QImage(self.mat)
        self.layer.updatePixmap(image)
        QDialog.reject(self)

    def initUI(self, parent):
        self.setWindowTitle('伽马调整控制器')
        # 定位
        self.resize(160, 160)
        pos = parent.geometry()
        self.move((pos.width() - self.width()) / 2, (pos.height() - self.height()) / 2)
        # 信号
        #       对话框确定
        self.DialogButtonBox.accepted.connect(self.accept)
        self.DialogButtonBox.rejected.connect(self.reject)
        # 参数
        self.doubleSpinBox_gamma.valueChanged.connect(self.updateSlot)
        self.doubleSpinBox_contrast.valueChanged.connect(self.updateSlot)

    def updateSlot(self):
        gamma = self.doubleSpinBox_gamma.value()
        contrast = self.doubleSpinBox_contrast.value()
        self.__gamma(gamma, contrast)

    def __gamma(self, gamma=0.455, contrast=1):
        """
        伽马变换
        Y = contrast * pow(X,gama)
        :param gama=: 伽马系数
        :param contrast: 对比度
        :return:
        """
        start = time.perf_counter()
        mat = self.mat.copy()
        # 映射表必须为0-255（改成其他会报错）
        gamma_table = [contrast * np.power(x / 255.0, gamma) * 255.0 for x in range(256)]
        gamma_table = np.uint8(np.clip(np.round(np.array(gamma_table)), 0, 255))
        mat[:, :, 0:3] = cv2.LUT(mat[:, :, 0:3], gamma_table)
        image = Converter.Numpy2QImage(mat)
        end = time.perf_counter()
        print('gamma', '耗时：', end - start)
        self.layer.updatePixmap(image)



Window = None  # 主窗体


def init(window):
    """
    初始化
    :param window: 主窗体
    :return:
    """
    global Window
    Window = window
    __menu()    # 创建菜单栏


def __menu():
    """
    将插件入口连接到菜单栏，这样，点击菜单栏按钮时，能使用本插件功能
    :return:
    """
    window = Window
    menuBar = window.menuBar()  # 菜单栏句柄
    menu_layer = menuBar.menu_layer  # 图层栏句柄
    menu_adjustment = menu_layer.menu_adjustment
    action = menuBar.newAction('Gamma变换', menuBar)  # 新建菜单栏选项
    action.func = newGamma  # 当按钮出发时，运行 newBlur 方法
    menu_adjustment.addAction(action)  # 把选项添加到 滤波 分类


def newGamma():
    window = Window  # 主窗体
    layer = window.currentLayer  # 获取当前图层句柄
    if layer:
        image = layer.image  # 当前图层QImage句柄
        mat = Converter.QImage2Numpy(image)  # 将QImage对象转化为numpy.array 对象
        controller = GammaController(window, mat)
        controller.layer = layer
        controller.updateSlot()  # 初始更新
        if controller.exec_():
            pass